<template>
  <div>
      <div class="el-cards">
          <el-card shadow="never" :body-style="{ padding: '0px' }" style="width: 98.5%" >
              <div style="padding: 10px">
                  <el-input clearable @change="projectPageAll" placeholder="请输入项目分类名称" style="width: 200px"
                            v-model="form.projectType"></el-input>
                  <el-input clearable @change="projectPageAll" placeholder="请输入创建人" style="width: 200px;margin-left: 10px"
                            v-model="form.username"></el-input>
                  <el-button @click="projectPageAll" style="margin-left: 10px" :icon="Search" type="info">查询</el-button>
                  <el-button @click="czhi" style="margin-left: 10px" :icon="Refresh" type="success">重置</el-button>
              </div>
          </el-card>
      </div>

    <el-card shadow="never" style="margin-left: 10px;margin-right: 10px" :body-style="{ padding: '0px' }">
      <div>
        <el-dialog v-model="dialogFormVisible" title="添加分类" width="500">
          <el-form>
            <el-form-item label="分类名称">
              <el-input v-model="projectType" placeholder="请输入分类名称"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="submitProjectAdd">
                提交
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <div>
        <el-dialog v-model="dialogFormVisibles" center title="批量添加分类" width="500">
          <el-upload v-model:file-list="fileList"
                     class="upload-demo"
                     drag
                     :http-request="uploadFile"
                     limit="1"
                     accept=".xlsx"
                     multiple
                     :on-progress="handleAvatarSuccess"
                     :on-remove="RemoveFile"
                     :on-change="handChange">
            <el-icon class="el-icon--upload">
              <upload-filled/>
            </el-icon>
            <div class="el-upload__text">
              选择Excel文件或 <em>拖拽上传</em>
            </div>
          </el-upload>
          <el-form-item>
            <div style="align-items: center">项目分类批量新增模板</div>
            <el-button @click="FileDownload" text size="small" type="success" style="margin-left: 5px;margin-top: 3px">
              点击下载
            </el-button>
          </el-form-item>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisibles = false">取消</el-button>
              <el-button type="primary" @click="submitAdds">
                提交
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <div>
        <el-dialog center v-model="dialogEditisible" title="修改分类" width="500">
          <el-form v-model="retuform">
            <el-form-item label="分类名称">
              <el-input v-model="retuform.projectType" placeholder="请输入分类名称"/>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogEditisible = false">取消</el-button>
              <el-button type="primary" @click="submitProjectEdit">
                提交
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <div class="search-title">
        <div style="margin-bottom: 10px">
          <el-button @click="projectTypeAddDialog" :icon="Plus" type="success">新增</el-button>
          <el-button @click="dialogFormVisibles = true" style="margin-left: 10px" :icon="FolderOpened" type="primary">
            批量新增
          </el-button>
          <el-button @click="Delects" style="margin-left: 10px" type="danger" :icon="DeleteFilled">批量删除</el-button>
          <el-button @click="ExportFile" type="warning" :icon="FolderChecked" style="margin-left: 10px">导出</el-button>
        </div>
        <el-table ref="multipleTableRef" :data="tableData" @selection-change="selectionChange" stripe fit
                  border="border">
          <template #empty>
            <el-empty :image-size="150"></el-empty>
          </template>
          <el-table-column type="selection" width="60"/>
          <el-table-column prop="id" label="类型ID" align="center" />
          <el-table-column prop="projectType" label="项目类型" align="center" />
          <el-table-column prop="creator" label="创建人" align="center" />
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column align="center">
            <template #header>
              <div>操作</div>
            </template>
            <template #default="scope">
              <el-button size="small" type="primary" text @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="small" type="danger" text @click="delect(scope.row,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
          <el-config-provider :locale="zhCn">
            <el-pagination
              v-model:current-page="currentPage2"
              v-model:page-size="pageSize"
              :page-sizes="[10, 15, 20, 25]"
              size="default"
              background="true"
              layout="total, sizes, prev, pager, next"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-config-provider>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import {ElConfigProvider, ElMessage, ElMessageBox} from 'element-plus'
import zhCn from "element-plus/es/locale/lang/zh-cn"
import {Search, FolderChecked, DeleteFilled, Refresh, FolderOpened, Plus, UploadFilled} from '@element-plus/icons-vue'
import {removeFile, getFile, uploadFileSave, uploadFileMerge, getRandomString} from '@/api/fileApi.js'
import {
  checkProjectType,
  exportFileExcel,
  projectTypeAdd,
  projectTypeAdds,
  projectTypeDelects,
  projectTypeEdit,
  projectTypePage
} from "../projectType/projectTypeApi.js";
import {useUserStore} from "@/pinia/stores/user";

const userStore = useUserStore()
const userData = userStore.userInfo
const dialogFormVisible = ref(false)
const dialogFormVisibles = ref(false)
const multipleTableRef = ref()
const types = ref('')
const currentPage2 = ref(1);
const pageSize = ref(10)
const tableData = ref([])
const total = ref(0)
let projectDelectIds = []
const fileList = ref([])
const form = reactive({
  projectType: '',
  username: ''
})
const projectType = ref("")
let retuform = reactive({
  creator: "",
  modifier: "",
  projectType: ""
})
const noform = () => {
  form.projectType = '',
    form.username = ''
}
const dialogEditisible = ref(false)
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage2.value = 1
  projectPageAll();
}
const handleCurrentChange = (val) => {
  currentPage2.value = val
  projectPageAll();
}
const projectTypeAddDialog = () => {
    projectType.value = ""
    dialogFormVisible.value = true
}
const delect = (data, index) => {
  projectDelectIds = []
  projectDelectIds.push(data.id)
  ElMessageBox.confirm(
    '确定要删除吗?',
    'Warning',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      let data = await projectTypeDelects(projectDelectIds)
      if (data.code === 0) {
        ElMessage.success("删除成功")
        projectPageAll();
      } else {
        ElMessage.error("删除失败")
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

const selectionChange = async (val) => {
  projectDelectIds = []
  for (let i = 0; i < val.length; i++) {
    projectDelectIds.push(val[i].id)
  }
}
const Delects = () => {
  if (projectDelectIds.length < 1) {
    ElMessage.error("请选择要删除的分类！")
  } else {
    ElMessageBox.confirm(
      '确定要删除这些分类吗?',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      let data = await projectTypeDelects(projectDelectIds)
      if (data.code === 0) {
        ElMessage.success("删除成功")
        projectPageAll();
        multipleTableRef.value.clearSelection();
      } else {
        ElMessage.error("删除失败")
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
  }
}

const ExportFile = () => {
  if (projectDelectIds.length < 1) {
    ElMessage.error("请选择要导出的数据！")
    return
  }
  const data = [];
  for (let i = 0; i < projectDelectIds.length; i++) {
    tableData.value.forEach(item => {
      if (item.id === projectDelectIds[i]) {
        data.push(item)
      }
    })
  }
  exportFileExcel(data);
  multipleTableRef.value.clearSelection();
}
const handleEdit = (index) => {
  dialogEditisible.value = true;
  retuform = index
}

const projectPageAll = async () => {
  let data = await projectTypePage(form, pageSize.value, currentPage2.value)
  tableData.value = data.data.records
  total.value = data.data.total
}
const czhi = () => {
  form.projectType = "";
  projectPageAll()
}
projectPageAll();

const FileDownload = async () => {
  let fileName = "项目分类批量添加Excel模板.xlsx";
  await getFile(fileName).then(res => {
    let fileUrl = 'http://localhost:8082/static/img/real/' + fileName;
    let extName = fileUrl.substring(fileUrl.lastIndexOf("."));
    const link = document.createElement('a');
    link.download = "项目分类添加Excel模板.xlsx"
    link.href = fileUrl
    link.target = "_blank";
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
  }).catch(res => {
    ElMessage.error(res.data.message)
  });
}
//新增
const submitProjectAdd = async () => {
  if (projectType.value === "") {
    ElMessage.error("请输入分类名称")
  } else if (projectType.value.length < 3) {
    ElMessage.error("分类名称长度3-20位")
  } else {
    await checkProjectType(projectType.value).then(async res => {
      if (res.code === 1) {
        ElMessage.error("分类名称已存在")
      } else if (res.code === 0) {
        await projectTypeAdd(projectType.value, userData.username).then(res => {
          if (res.code === 0) {
            ElMessage.success("新增成功")
            dialogFormVisible.value = false;
            projectType.value = "";
            projectPageAll();
          }
        }).catch(res => {
          ElMessage.error("新增失败")
        })
      }
    });

  }
}

const submitProjectEdit = async () => {
  if (retuform.projectType === "") {
    ElMessage.error("请输入分类名称")
  } else if (retuform.projectType.length < 3) {
    ElMessage.error("项目分类名称长度3-20位")
  } else {
    await checkProjectType(retuform.projectType).then(async res => {
      if (res.code === 1) {
        ElMessage.error("分类名称已存在")
      } else {

        await projectTypeEdit(retuform, userData.username).then(res => {
          if (res.code === 0) {
            ElMessage.success("修改成功")
            dialogEditisible.value = false;
            projectPageAll();
            retuform.projectType = "";
          }
        }).catch(res > {})
      }
    })
  }
}

const submitAdds = async () => {
  if (fileList.value.length === 0) {
    ElMessage.error("请选择文件")
  } else {
    await projectTypeAdds(fileList.value[0].name, userData.username).then(res => {
      if (res.code === 0) {
        ElMessage.success("提交成功")
        dialogFormVisibles.value = false
        fileList.value = []
        projectPageAll();
      } else {
        ElMessage.error("添加失败")
      }
    }).catch(res => {
      ElMessage.error("添加失败")
    })
  }
}

const uploadFile = () => {
}
const RemoveFile = async (uploadFile, uploadFiles) => {
  let fileName = "";
  if (uploadFile !== null) {
    fileName = uploadFile.raw.name;
  }

  await getFile(fileName).then(res => {
    if (res.data.length > 0) {
      removeFile(fileName).then(res => {

      }).catch(res => {
      });
    }
  }).catch(res => {
    ElMessage.error(res.error);
  })
}

const handleAvatarSuccess = () => {

}
const handChange = async (file, fileList) => {
  const {name, size, raw: uploadFile} = file;
  let guid = getRandomString(30);
  // 1,检查分片  2,分片上传 3,合并
  // 检查分片，看是否已经上传一部分，要不要继续上传
  let index = 0; //默认分片
  let chunkSize = 5 * 1024 * 1024; //每一个分片为5M
  let start = chunkSize * index;
  let dir = '';//临时目录名
  while (start < size) {
    let blob = null;
    if (start + chunkSize > size) {
      blob = uploadFile.slice(start, size)
    } else {
      blob = uploadFile.slice(start, start + chunkSize)
    }
    start += chunkSize; //分片累加
    //分片上传
    let boltFile = new File([blob], name);
    let formData = new FormData;
    formData.append('file', boltFile)
    formData.append('chunk', index)
    formData.append('guid', guid)
    let res = await uploadFileSave(formData);
    dir = res.data;
    index += 1;
  }
  //合并
  let extList = name.split(".")
  let ext = extList[extList.length - 1];
  let formData1 = new FormData;
  formData1.append("guid", guid);
  formData1.append("fileName", name);
  let res = await uploadFileMerge(formData1);
}


</script>
<style scoped lang="scss">
.search-title {
  margin: 10px;
}

.demo-pagination-block {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  text-align: center;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-cards {
  // 内容垂直居中，靠右显示
  display: flex;
  justify-content: left;
  width: 100%;
  margin: 10px;
}


</style>
